/**
 * Functions save in db
 * */
var EasyMongo = require('../../common').EasyMongo;

var executorName = 'iview';
initExecutor(executorName);

/**
 *  @param executor series name
 * */
function initExecutor(name) {
    EasyMongo.remove('executor', {name:name}, function () {
        EasyMongo.add('executor', [ {
            name: name,
            col: "exceptionKey",
            method: function (data) {
                /**
                 * Real exceptionKey is a vector with 4 dimension, unique exception,
                 * but for better performance, just save error message & trace segments here.
                 * when calculate real key, this attribute should combine with type(attribute), weight(global)
                 * */
                var vector = [];
                var start = data.match(/Exception:/).index + 10;
                var end = data.match(/\n.+\s+at\s+/).index;
                vector.push(data.substring(start,end));

                var temp = data.split("\n");
                var traceSegment = "";
                for(var i = 0,j=0;i<temp.length;i++) {
                    if(temp[i].match(/\s+at\s+/)) {
                        if(++j<=5 || temp[i].match(/\.wos\./)) {
                            traceSegment += temp[i].substring(temp[i].indexOf("(")+1, temp[i].lastIndexOf(")"));
                        } else {
                            break;
                        }
                    }
                }
                vector.push(traceSegment);
                console.log("IView Source Executor 1: Slice Exception Key");
                return vector;
            }
        }, {
            name: name,
            col: "exceptionType",
            filter: "R/\\.(\\w+Exception):/i$1",
            method:function(data,afterFilter){
                console.log("IView Source Executor 2: Fetch Exception Type");
                return afterFilter;
            }
        }, {
            name: name,
            col: "lastAppear",
            filter: "S(0,19)",
            method:function(data,afterFilter){
                console.log("IView Source Executor 3: Set LastAppearTime");
                return new Date(afterFilter).valueOf();
            }
        }, {
            name: name,
            col: "createdAt",
            filter: "S(0,19)",
            method:function(data,afterFilter){
                console.log("IView Source Executor 4: Set Discover Time");
                return new Date(afterFilter).valueOf();
            }
        }, {
            name: name,
            col: "trace",
            filter: "R/\\.(\\w+Exception):(.+)/i$2",
            method: function (data,afterFilter) {
                console.log("IView Source Executor 5: Fetch Stack Trace");
                return !!data ? afterFilter+data.substring(data.indexOf("\n")).trim() : afterFilter;
            }
        }
        ], function (err, ids) {
        });
    });
}